<template>
  <div>
    <!-- 导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片警告区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon>
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_pot">
        <el-col>
          <span>选择商品分类: </span>
          <!-- 多层分级区域 -->
          <el-cascader :options="cateList" v-model="selectCateKey" :props="eascaderList" clearable
            @change="handleChange" placeholder="请选择">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab区域 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleTab">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="mini" type="primary" :disabled="btnDisable" @click="addDialogVisible=true">添加参数</el-button>
          <!-- 动态参数区域 -->
          <el-table :data="manyTabsDate" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand" width="50%">
              <template v-slot="{row}">
                <el-tag v-for="(item,ind) in row.attr_vals" :key="ind" closable @close="handleClose(ind,row)">{{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <!-- 确定按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50%">
            </el-table-column>
            <el-table-column prop="attr_name" label="动态参数">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{row}">
                <!-- 编辑按钮 -->
                <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(row.attr_id)">
                  修改
                </el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(row.attr_id)"> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="btnDisable" @click="addDialogVisible=true">添加属性</el-button>
          <!-- 静态属性区域 -->
          <el-table :data="onlyTabsDate" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand" width="50%">
              <template v-slot="{row}">
                <el-tag v-for="(item,ind) in row.attr_vals" :key="ind" closable @close="handleClose(ind,row)">{{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <!-- 确定按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50%">
            </el-table-column>
            <el-table-column prop="attr_name" label="静态属性">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{row}">
                <!-- 编辑按钮 -->
                <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(row.attr_id)">
                  修改
                </el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(row.attr_id)"> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加分类 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" @close="resetaddForm" width="50%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name" class="is-required">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改编辑 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" @close="reseteditForm" width="50%">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name" class="is-required">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      // 商品分类列表
      cateList: [],
      //   多级联选择器配置
      eascaderList: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: 'true'
      },
      // 多级联动选择器所选择的数组
      selectCateKey: [],
      activeName: 'many',  // tab栏
      manyTabsDate: [],
      onlyTabsDate: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { require: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      inputVisible: false,  // 控制newtag隐藏显示
      inputValue: ''
    }
  },
  methods: {
    // 小tag删除方法
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.setAttrVals(row)
    },
    // 独立封装put方法  因为与删除接口相同  多次复用
    async setAttrVals (row) {
      // 提交参数
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success(res.meta.msg)
      //   this.getParamsData()
      //   row.inputVisible = false
    },
    // 失去焦点
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 输入空格为有效内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求
      this.setAttrVals(row)
    },
    // newTag绑定事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 删除
    async removeParams (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`, {
        attr_sel: this.activeName,
        attr_name: this.editForm.attr_name
      })
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 提交修改
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_sel: this.activeName,
          attr_name: this.editForm.attr_name
        })
        if (res.meta.status !== 200) return this.$message.error('获取数据失败')
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 监听重置编辑修改窗口
    reseteditForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑窗口
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 添加分类的点击事件
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 监听添加表单
    resetaddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // tab栏点击切换事件
    handleTab () {
      //   console.log(this.activeName);
      this.getParamsData()
    },
    // 获取参数数据
    async getParamsData () {
      // 取消一二级的选择
      if (this.selectCateKey.length !== 3) {
        return this.selectCateKey = []
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // 遍历attr_vals属性进行字符串拼接
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [],
          // 控制单个newTag
          item.inputValue = '',
          item.inputVisible = false
      })
      if (this.activeName === 'many') {
        this.manyTabsDate = res.data
      } else {
        this.onlyTabsDate = res.data
      }
    },
    // 联动选择器触动的方法
    handleChange () {
      // 取消一二级的选择
      if (this.selectCateKey.length !== 3) {
        this.selectCateKey = []
        this.manyTabsDate = []
        this.onlyTabsDate = []
        return
      }
      this.getParamsData()
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.cateList = res.data
    }
  },
  computed: {
    btnDisable () {
      if (this.selectCateKey.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId () {
      if (this.selectCateKey.length === 3) {
        return this.selectCateKey[2]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    // 获取商品分类列表
    this.getCateList()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
.cat_pot {
  margin: 20px 0;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.button-new-tag,
.el-tag {
  margin: 10px;
}
.input-new-tag {
  margin: 10px;
  width: 120px;
}
</style>